<template>
  <div class="head">
    <div
      class="left"
      @click="backindex()"
      v-show="
        this.$route.path != '/TheThink' &&
        this.$route.path != '/TheLook' &&
        this.$route.path != '/TheWant'
      "
    >
      <button class="btn btn-primary btn-snake-border">
      <div class="btn-borders">
        <div class="border-top"></div>
        <div class="border-right"></div>
        <div class="border-bottom"></div>
        <div class="border-left"></div>
      </div>
      <span class="btn-text">返回主页</span>
    </button>
    </div>

    <div class="right">
      <div class="login" v-if="!Islogin">
        <el-button
          type="success"
          icon="el-icon-position"
          size="small"
          @click="ToLogin()"
          >登录</el-button
        >
        <el-button
          type="success"
          icon="el-icon-s-custom"
          size="small"
          @click="Toregistered()"
          >注册</el-button
        >
      </div>
      <div class="admin" v-else>
        <el-col :span="12">
          <el-dropdown trigger="click" type="primary">
            <span class="el-dropdown-link">
              欢迎您！ <br />{{ this.$store.state.admin
              }}<i class="el-icon-caret-bottom"></i>
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item icon="el-icon-postcard"
                ><span @click="LookInfo()">个人资料</span></el-dropdown-item
              >
              <el-dropdown-item icon="el-icon-close"
                ><span @click="exit()">退出登录</span></el-dropdown-item
              >
            </el-dropdown-menu>
          </el-dropdown>
        </el-col>
      </div>
    </div>
    <!-- 个人信息 -->
    <el-drawer :visible.sync="drawer" :with-header="false">
      <span class="title">个人信息</span>
      <p>IDCard</p>
      <p>Name:{{ this.$store.state.admin }}</p>
      <p>Tel:{{ this.$store.state.phone }}</p>
    </el-drawer>
    <!-- 登录 -->
    <el-dialog title="登录" :visible.sync="dialogFormVisible">
      <el-form :model="form">
        <el-form-item label="账号:" :label-width="formLabelWidth">
          <el-input
            v-model="form.phone"
            autocomplete="off"
            placeholder="账号为注册时的手机号"
          ></el-input>
        </el-form-item>
        <el-form-item label="密码:" :label-width="formLabelWidth">
          <el-input
            v-model="form.password"
            autocomplete="off"
            show-password
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="login()">登录</el-button>
      </div>
    </el-dialog>
    <!-- 注册 -->
    <el-dialog title="注册" :visible.sync="registered">
      <el-form
        :model="ruleForm2"
        status-icon
        :rules="rules2"
        ref="ruleForm2"
        label-width="0"
        class="demo-ruleForm"
      >
        <el-form-item prop="name">
          <el-input
            v-model="ruleForm2.name"
            auto-complete="off"
            placeholder="请输入你的昵称"
            maxlength="10"
          ></el-input>
        </el-form-item>
        <el-form-item prop="tel">
          <el-input
            v-model="ruleForm2.tel"
            auto-complete="off"
            placeholder="请输入手机号"
          ></el-input>
        </el-form-item>
        <!-- <el-form-item prop="smscode" class="code">
            <el-input v-model="ruleForm2.smscode" placeholder="验证码"></el-input>
            <el-button type="primary" :disabled='isDisabled' @click="sendCode">{{buttonText}}</el-button>
          </el-form-item> -->
        <el-form-item prop="pass">
          <el-input
            type="password"
            v-model="ruleForm2.pass"
            auto-complete="off"
            placeholder="输入密码"
          ></el-input>
        </el-form-item>
        <el-form-item prop="checkPass">
          <el-input
            type="password"
            v-model="ruleForm2.checkPass"
            auto-complete="off"
            placeholder="确认密码"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            @click="submitForm('ruleForm2')"
            style="width: 100%"
            >注册</el-button
          >
          <p class="login" @click="gotoLogin">已有账号？立即登录</p>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="registered = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
export default {
  inject: ["reload"],
  data() {
    // <!--验证手机号是否合法-->
    let checkTel = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入手机号码"));
      } else if (!this.checkMobile(value)) {
        callback(new Error("手机号码不合法"));
      } else {
        callback();
      }
    };
    //  <!--验证码是否为空-->
    // let checkSmscode = (rule, value, callback) => {
    //   if (value === '') {
    //     callback(new Error('请输入手机验证码'))
    //   } else {
    //     callback()
    //   }
    // }
    // <!--验证密码-->
    let validatePass = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入密码"));
      } else {
        if (this.ruleForm2.checkPass !== "") {
          this.$refs.ruleForm2.validateField("checkPass");
        }
        callback();
      }
    };
    // <!--二次验证密码-->
    let validatePass2 = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请再次输入密码"));
      } else if (value !== this.ruleForm2.pass) {
        callback(new Error("两次输入密码不一致!"));
      } else {
        callback();
      }
    };
    return {
      admin: this.$store.state.Admin,
      Islogin: this.$store.state.isLogin,
      //个人信息弹窗
      drawer: false,
      //登录
      dialogFormVisible: false,
      form: {
        name: "",
        phone: "",
        password: "",
      },
      formLabelWidth: "80px",
      timer: null,
      //注册
      registered: false,
      ruleForm2: {
        name: "",
        pass: "",
        checkPass: "",
        tel: "",
        // smscode: ""
      },
      rules2: {
        pass: [{ validator: validatePass, trigger: "change" }],
        checkPass: [{ validator: validatePass2, trigger: "change" }],
        tel: [{ validator: checkTel, trigger: "change" }],
      },
      // buttonText: '发送验证码',
      // isDisabled: false, // 是否禁止点击发送验证码按钮
      flag: true,
      
    };
  },
  mounted(){
    //登录验证
    if(this.Islogin == false){
      this.$swal.fire({
          icon: "question",
          title: "请先登录哦!",
          showCloseButton: true,
          // 点击ok按钮的回调
          preConfirm: () => {
            this.dialogFormVisible = true;
          },
        }); 
    }
  },
  methods: {
    //返回主页
    backindex() {
      let NowUrl = this.$route.path;
      if (
        NowUrl != "/TheThink" &&
        NowUrl != "/TheLook" &&
        NowUrl != "/TheWant"
      ) {
        this.$router.push("/TheThink");
      }
    },
    //显示登录
    ToLogin() {
      this.dialogFormVisible = true;
    },
    //显示注册
    Toregistered() {
      this.registered = true;
    },
    //查看个人信息
    LookInfo() {
      this.drawer = true;
    },
    //退出登录
    exit() {
      let Exit = false;
      // 提交修改vuex数据
      this.$store.commit("exit", Exit);
      // 存储修改后的数据
      sessionStorage.setItem("store", JSON.stringify(this.$store.state));
      this.reload();
    },
    //验证登录
    login() {
      let tel = this.form.phone;
      //判断是否输入账号密码
      if (!tel) {
        this.dialogFormVisible = false;
        this.$swal.fire({
          icon: "error",
          title: "账号或密码不能为空！",
          showCloseButton: true,
          // 点击ok按钮的回调
          preConfirm: () => {
            this.dialogFormVisible = true;
          },
        });
      }
      // 发起请求
      this.$http
        .post(
          "/api/user/selectUser",
          {
            username: tel,
          },
          {}
        )
        .then((response) => {
          if (
            this.form.phone == response.data[0].phone &&
            this.form.password == response.data[0].password
          ) {
           // console.log(response); 显示出数据库数据
            this.$swal.fire({
              icon: "success",
              title: "登录成功！",
              showCloseButton: true,
              preConfirm: () => {
                //登录成功刷新页面
                this.reload();
              },
            });
            // 关闭登录界面
            this.dialogFormVisible = false;
            let n = true;
            let Admin = response.data[0].id;
            let Phone = response.data[0].phone;
            let user = {
              islogin: n,
              name: Admin,
              phone: Phone,
            };
            //提交vuex处理
            this.$store.commit("loginRe", user);
            //  存储用户信息，下次刷新读取刷新前的用户数据  解决了刷新数据消失
            sessionStorage.setItem("store", JSON.stringify(this.$store.state));
          } else {
            this.dialogFormVisible = false;
            this.$swal.fire({
              icon: "error",
              title: "账号或密码有误！",
              showCloseButton: true,
              // 点击ok按钮的回调
              preConfirm: () => {
                this.dialogFormVisible = true;
              },
            });
          }
        });
    },
    //注册
    // <!--发送验证码-->
    // sendCode () {
    //   let tel = this.ruleForm2.tel
    //   if (this.checkMobile(tel)) {
    //     console.log(tel)
    //     let time = 60
    //     this.buttonText = '已发送'
    //     this.isDisabled = true
    //     if (this.flag) {
    //       this.flag = false;
    //       let timer = setInterval(() => {
    //         time--;
    //         this.buttonText = time + ' 秒'
    //         if (time === 0) {
    //           clearInterval(timer);
    //           this.buttonText = '重新获取'
    //           this.isDisabled = false
    //           this.flag = true;
    //         }
    //       }, 1000)
    //     }
    //   }
    // },
    // <!--提交注册-->
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let names = this.ruleForm2.name;
          let pass = this.ruleForm2.pass;
          let tel = this.ruleForm2.tel;
          // 发起请求
          this.$http
            .post(
              "/api/user/addUser",
              {
                name: names,
                password: pass,
                phone: tel,
              },
              {}
            )
            .then((response) => {
              console.log(response);
            });
          setTimeout(() => {
            this.$swal.fire({
              icon: "success",
              title: "注册成功！",
              showCloseButton: true,
            });
            // 验证密码
            this.$refs[formName].resetFields();
            this.registered = false;
          }, 400);
        } else {
          return false;
        }
      });
    },
    // 切换登录
    gotoLogin() {
      this.registered = false;
      this.dialogFormVisible = true;
    },
    // 验证手机号
    checkMobile(str) {
      let re = /^1\d{10}$/;
      if (re.test(str)) {
        return true;
      } else {
        return false;
      }
    },
  },
};
</script>
<style  scoped>
@import "../css/head.css";
</style>
